﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Jayden.Dll.Cards.Poker;
using System.Threading;
using System.IO;

namespace Jayden.Windows.PokerClient
{
	public partial class LoginForm : Form
	{
		private WindowsPokerClient m_PokerClient;
		private Thread m_Thread;

		public LoginForm(string[] args)
		{
			if (!(DesignMode || LicenseManager.UsageMode == LicenseUsageMode.Designtime))
			{
				string defaultHost = "localhost";
				if (File.Exists("server.txt"))
					defaultHost = File.ReadAllLines("server.txt")[0];
				else
					File.WriteAllLines("server.txt", new string[] { defaultHost });
				string host = args.Length > 0 ? args[0] : defaultHost;
				int port = args.Length > 1 ? int.Parse(args[1]) : PokerProtocol.DefaultPort;
				m_PokerClient = new WindowsPokerClient(host, port);
				m_PokerClient.LoginForm = this;
				m_Thread = new Thread(m_PokerClient.Run);
				m_Thread.IsBackground = true;
			}
			InitializeComponent();

			string[] username = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split('\\');

			tbLogin.Text = username.Length == 1 ? username[0] : username[1];
			tbPassword.Text = "password";

			if(m_Thread != null)
				m_Thread.Start();
		}

		protected override void OnClosed(EventArgs e)
		{
			base.OnClosed(e);

			m_Thread.Abort();
		}

		public string Login { get { return tbLogin.Text; } }
		public string Password { get { return tbPassword.Text; } }

		public bool LoginEnabled
		{
			get { return bLogin.Enabled; }
			set { bLogin.Enabled = value; }
		}

		private void bLogin_Click(object sender, EventArgs e)
		{
			m_PokerClient.LogIn(Login, Password);
			bLogin.Enabled = false;
		}
	}
}
